package com.group.sliding.interceptor;

import com.group.sliding.properties.AdminProperties;
import com.group.sliding.context.AdminContext;
import com.group.sliding.context.UserContext;
import com.group.sliding.exception.UnauthorizedException;
import com.group.sliding.utils.CollUtils;
import com.group.sliding.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Slf4j
@Component
@RequiredArgsConstructor
public class LoginInterceptor implements HandlerInterceptor {

    private final JwtTool jwtTool;
    private final AdminProperties adminProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            // 没匹配到路径，给全局异常处理controller处理
            return true;
        }

        // 获取请求头中的 token
        String token = request.getHeader("authorization");
        if (token == null) {
            throw new UnauthorizedException("未登录");
        }
        if (token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        // 校验token
        Long userId = jwtTool.parseToken(token);
        // 存入上下文
        UserContext.setUser(userId);
        // 获取用户id，判断是否管理员
        List<Long> admins = adminProperties.getAdmins();
        AdminContext.setAdmin(CollUtils.isNotEmpty(admins) && admins.contains(userId));
        // 放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清理用户
        UserContext.removeUser();
    }
}
